package top.went.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.went.db.dao.CustomerDao;
import top.went.db.dao.SaleOppDao;
import top.went.db.dao.UserDao;
import top.went.db.mapper.SaleOppMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.CustomerEntity;
import top.went.pojo.SaleOppEntity;
import top.went.utils.CodeGenerator;
import top.went.utils.TrackLog;
import top.went.vo.PageEntity;
import top.went.vo.SaleOppVo;

import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class SaleOppService {
    @Autowired
    private SaleOppDao saleOppDao;
    @Autowired
    private SaleOppMapper saleOppMapper;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private UserDao userDao;

    private static final Map<String,String> map = new HashMap<>();

    static {
        map.put("oppId","opp_id");
        map.put("oppTheme","opp_theme");
        map.put("tbCustomerByCusId.cusName","cus_name");
        map.put("tbContactsBy联系人Id.cotsName","cots_name");
        map.put("priority","priority");
        map.put("classification","classification");
        map.put("tbUserByUserId.userName","user_name");
        map.put("expectedTime","expected_time");
        map.put("expectedAmount","expected_amount");
        map.put("possibility","possibility");
        map.put("stage","stage");
        map.put("oppStatus","opp_status");
        map.put("stageStartTime","stage_start_time");
        map.put("updateTime","update_time");
    }

    /**
     * 搜寻某个客户对应的所有机会
     * @param cusId
     * @return
     */
    public List<SaleOppEntity> findAllByTbCustomerByCusIdAndIsDelete(Integer cusId){
//        CustomerEntity customerEntity = new CustomerEntity();
//        customerEntity.setCusId(cusId.intValue());
        CustomerEntity customerEntity = customerDao.findOne(cusId);
        if (customerEntity == null)
            return null;
        return  saleOppDao.findAllByTbCustomerByCusIdAndIsDelete(customerEntity, 0L);
    }

    /**
     * 客户视图
     * @param id
     * @return
     */
    public List<SaleOppEntity> loadAllByCusId(Long id) {
        List<SaleOppEntity> saleOppEntities = saleOppMapper.loadAllByCusId(id);
        /*if(saleOppEntities == null){
            throw new NotFoundException("没有对应的机会！");
        }*/
        return saleOppEntities;
    }

    public static void main(String[] args) {
        System.out.println("kan"+CodeGenerator.orderGenerator(false));
    }

    /**
     * 添加销售机会
     * @param saleOppEntity
     * @return
     * @throws ServiceException
     */
    public boolean addSaleOpp(SaleOppEntity saleOppEntity) throws ServiceException {
        try {
            if(saleOppEntity.getTbContactsBy联系人Id() == null || saleOppEntity.getTbContactsBy联系人Id().getCotsId() == null)
                saleOppEntity.setTbContactsBy联系人Id(null);
            if(saleOppEntity.getTbUserByUserId() == null || saleOppEntity.getTbUserByUserId().getUserId() == null)
                saleOppEntity.setTbUserByUserId(null);
            if (saleOppEntity.getTbCustomerByCusId() == null || saleOppEntity.getTbCustomerByCusId().getCusId() == null)
                saleOppEntity.setTbCustomerByCusId(null);
            return saleOppDao.save(saleOppEntity) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("添加销售机会失败");
        }
    }

    /**
     * 修改销售机会
     * @param saleOppEntity
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean modifySaleOpp(SaleOppEntity saleOppEntity) throws NotFoundException, ServiceException {
        SaleOppEntity saleOppEntity1 = load(saleOppEntity.getOppId());
        saleOppEntity.setTrackLog(saleOppEntity1.getTrackLog());
        System.out.println("we"+saleOppEntity1.getStage());
        /*if(saleOppEntity.getCustomerDemand()!=null && saleOppEntity.getTbCustomerByCusId() != saleOppEntity1.getTbCustomerByCusId()){
            throw new ServiceException("客户不能更改！");
        }*/
        if(saleOppEntity.getTbCustomerByCusId() != null && saleOppEntity.getTbCustomerByCusId().getCusId() != null){
            saleOppEntity1.setTbCustomerByCusId(saleOppEntity.getTbCustomerByCusId());
        }
        saleOppEntity1.setOppTheme(saleOppEntity.getOppTheme());
        saleOppEntity1.setOppStatus(saleOppEntity.getOppStatus());
        if (saleOppEntity.getTbContactsBy联系人Id() != null && saleOppEntity.getTbContactsBy联系人Id().getCotsId() != null){
            saleOppEntity1.setTbContactsBy联系人Id(saleOppEntity.getTbContactsBy联系人Id());
        } else {
            saleOppEntity1.setTbContactsBy联系人Id(null);
        }
        saleOppEntity1.setClassification(saleOppEntity.getClassification());
        saleOppEntity1.setDiscoveryTime(saleOppEntity.getDiscoveryTime());
        saleOppEntity1.setOppSource(saleOppEntity.getOppSource());
        if (saleOppEntity.getTbUserByUserId() != null && saleOppEntity.getTbUserByUserId().getUserId() != null){
            saleOppEntity1.setTbUserByUserId(saleOppEntity.getTbUserByUserId());
        } else {
            saleOppEntity1.setTbUserByUserId(null);
        }
        saleOppEntity1.setCustomerDemand(saleOppEntity.getCustomerDemand());
        saleOppEntity1.setExpectedTime(saleOppEntity.getExpectedTime());
        saleOppEntity1.setExpectedAmount(saleOppEntity.getExpectedAmount());
        saleOppEntity1.setPossibility(saleOppEntity.getPossibility());
        saleOppEntity1.setPriority(saleOppEntity.getPriority());
        if(!saleOppEntity1.getStage().equalsIgnoreCase(saleOppEntity.getStage())){
            saleOppEntity1.setStage(saleOppEntity.getStage());
            saleOppEntity1.setStageStartTime(new java.sql.Date(new Date().getTime()));
            String trackLog = TrackLog.getTrack(saleOppEntity,saleOppEntity.getStage());
            saleOppEntity1.setTrackLog(trackLog);
        }
        saleOppEntity1.setStageRemarks(saleOppEntity.getStageRemarks());
        saleOppEntity1.setIntendProduct(saleOppEntity.getIntendProduct());
        saleOppEntity1.setUpdateTime(new java.sql.Date(new Date().getTime()));
        try {
            saleOppDao.save(saleOppEntity1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("机会修改失败！");
        }
    }

    /**
     * 删除机会
     * @param id
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteSaleOpp(Long id) throws NotFoundException, ServiceException {
        SaleOppEntity saleOppEntity = load(id);
        //外键检查（未完成）
        saleOppEntity.setIsDelete(1L);
        try {
            saleOppDao.save(saleOppEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("删除失败");
        }
    }

    /**
     * 编辑删除
     * @param ids
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteSelectedSaleOpp(Long[] ids) throws NotFoundException, ServiceException {
        for(int i=0; i<ids.length; i++){
            deleteSaleOpp(ids[i].longValue());
        }
        return true;
    }

    /**
     * 加载机会
     * @param id
     * @return
     */
    public SaleOppEntity load(Long id) throws NotFoundException {
        SaleOppEntity saleOppEntity = saleOppDao.findAllByOppIdAndIsDelete(id,0L);
        if (saleOppEntity == null)
            throw new NotFoundException("机会不存在");
        return saleOppEntity;
    }

    /**
     * 加载所有机会
     * @return
     */
//    public List<SaleOppEntity> loadList(){
//        return saleOppDao.findAllByIsDelete(0L);
//    }

    public PageEntity<SaleOppEntity> loadListPage(Integer pageNumber, Integer pageSize){
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize);
        List<SaleOppEntity> list = saleOppDao.findAllByIsDelete(0L,pageRequest);
        PageEntity pageEntity = new PageEntity((long) saleOppDao.findAllByIsDelete(0L).size(),list);
        return pageEntity;
    }

    /**
     * 快速查询机会（阶段、状态、类型、优先、阶段停留）
     * @param pageNumber
     * @param pageSize
     * @param stage
     * @param oppStatus
     * @param classification
     * @param priority
     * @param min
     * @param max
     * @return
     */
    public PageEntity<SaleOppEntity> loadListWhere(Integer pageNumber, Integer pageSize, String stage,
                                                   String oppStatus, String classification, String priority,String oppTheme, Long min, Long max){
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize);
        List<SaleOppEntity> list = saleOppDao.findAllByIsDeleteWhere(0L,stage,oppStatus,classification,priority,oppTheme,min,max,pageRequest);
        List<SaleOppEntity> list1 = new ArrayList<>();
        PageEntity pageEntity = new PageEntity((long) list.size(),list);
        return pageEntity;
    }

    /**
     * 机会高级查询
     * @param saleOppVo
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager-my")
    public PageEntity<SaleOppEntity> findAllSeniorSearch(SaleOppVo saleOppVo, Integer pageNumber, Integer pageSize){
        String order = saleOppVo.getPage().getSort(map);
        if(order.length() <= 0){
            order = "opp_id desc";
        }
        Page<SaleOppEntity> page = PageHelper.startPage(pageNumber,pageSize,order+" nulls last");
        saleOppMapper.findAllSeniorSearch(saleOppVo);
        return new PageEntity<>(page.getTotal(),page.getResult());
    }

    /**
     * 加载销售机会视图
     * @param id
     * @return
     * @throws NotFoundException
     */
    public SaleOppEntity loadDetailById(Long id) throws NotFoundException {
        SaleOppEntity saleOppEntity = saleOppMapper.loadSaleOppDetailById(id);
        if(saleOppEntity == null){
            throw new NotFoundException("未找到！");
        }
        return saleOppEntity;
    }

    /**
     * 销售机会饼状图统计
     * @param state
     * @return
     * @throws ServiceException
     */
    public List findAllForStatistic(String state) throws ServiceException{
        try{
            List<Map> type = saleOppMapper.findForStatistic(state);
            return type;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("获取销售机会数据异常");
        }
    }

    public long countByUser(Long userId)throws ServiceException{
        try {
            return saleOppDao.countAllByTbUserByUserIdAndIsDelete(userDao.findUserByOne(0L,userId),0L);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("统计失败");
        }
    }
    public long countByMonth()throws ServiceException{
        try {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            System.out.println("阿森纳反对票使得房价必将："+year+","+month);
            return saleOppDao.countAllByMonth(year, month);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("统计失败");
        }
    }
}
